﻿using Dapper;
using Dapper.Contrib.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Model;
using Tauren.Business.Entity.Output;
using Tauren.Business.Infrastructure.Globals;

namespace Tauren.Business.DLL.DictionaryDLL
{
    public class DictionaryBusiness : Base.BaseDLL, IDictionaryBusiness
    {
        public DictionaryBusiness(IConnectionDLLBase _dLLBase) : base(_dLLBase)
        {
        }

        public bool AddRes(List<DictionaryRes> Res, long DicId)
        {
            this.dbConnection.Execute($"delete  from `dictionary_res` where DicId = @DicId;", new DictionaryRes { DicId = DicId });
            if (Res.Any())
            {
                Res.ForEach(o => { o.DicId = DicId; });
                return this.dbConnection.Insert(Res) >= 0;
            }
            return true;
        }

        public List<DictionaryRes> GetRes(long AutoId) => this.dbConnection.Query<DictionaryRes>("select autoid, dicId, `language`, value  from dictionary_res where DicId = @DicId;", new DictionaryRes { DicId = AutoId }).AsList();

        public decimal GetSeq()
        {
            Dictionary dictionary = this.dbConnection.QueryFirstOrDefault<Dictionary>("SELECT * FROM dictionary WHERE havedelete=0  ORDER BY autoid DESC LIMIT 0,1");
            if (dictionary is null) return 1;
            else return (dictionary.Sequence is null ? 1 : dictionary.Sequence.Value + 1);
        }

        public bool IsPermissionCodeRepeat(long AutoId, string Code)
        {
            string sql = $"SELECT * FROM dictionary WHERE code='{Code}'";
            if (AutoId != 0)
            {
                sql = $"{sql} AND autoid != {AutoId}";
            }
            return dbConnection.Query<Dictionary>(sql).Any();
        }

        public List<PageDictionaryTable> Pages(QueryModel queryModel, out long Total)
        {
            Total = 0;
            string where = "";
            if (!string.IsNullOrEmpty(queryModel.KeyWord))
            {
                where += $"   AND r.code LIKE '%{queryModel.KeyWord}%' OR rs.value LIKE '%{queryModel.KeyWord}%' ";
            }
            if (string.IsNullOrEmpty(queryModel.SortField))
            {
                queryModel.SortField = "sequence";
                queryModel.IsAsc = false;
            }
            else
            {
                queryModel.SortField = queryModel.SortField.ToLower().Replace("dic_", "").Replace("dic", "").Trim();
            }
            if (queryModel.paramters.Any())
            {
                foreach (var item in queryModel.paramters)
                {
                    if (!string.IsNullOrEmpty(item.Value + ""))
                        where += $" AND r.{item.Label}={item.Value} ";
                    else where += $" AND r.parentId=0 ";
                }
            }
            else
            {
                where += $" AND r.parentId=0 ";
            }
            string asc = queryModel.IsAsc ? "ASC" : "DESC";
            queryModel.Page = queryModel.Page == 0 ? 1 : queryModel.Page;
            StringBuilder sql = new StringBuilder();
            sql.Append(@$"SELECT count(r.AutoId) as cnt FROM dictionary r LEFT JOIN dictionary_res rs ON r.autoid =rs.dicid  
                          AND rs.`language` = '{this.Global.Language}'  WHERE r.havedelete !=1
                        {where}  ;");
            sql.Append(@$"SELECT  r.autoid,r.parentId,r.code,r.`type` ,r.enable,rs.`language` ,rs.value,r.creator ,r.creatdate ,r.modifier ,r.modifdate 
                          FROM dictionary r LEFT JOIN dictionary_res rs ON r.autoid =rs.dicid  
                          AND rs.`language` = '{this.Global.Language}' WHERE r.havedelete !=1
                        {where}  ORDER BY {queryModel.SortField} {asc} LIMIT {(queryModel.Page - 1) * queryModel.PageSize},{ queryModel.PageSize} ;");
            using (var reader = dbConnection.QueryMultiple(sql.ToString()))
            {
                Total = reader.ReadFirstOrDefault<int>();
                List<PageDictionaryTable> pageModules = reader.Read<PageDictionaryTable>().ToList();
                long RowNo = ((queryModel.Page == 0 ? 1 : queryModel.Page) - 1) * queryModel.PageSize + 1;
                pageModules.ForEach(o =>
                {
                    o.RowNo = RowNo;
                    RowNo++;
                });
                return pageModules;
            }
        }
    }
}
